package com.sptpc.learnspring.controller.filter;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.sptpc.learnspring.global.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerExceptionResolver;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;

@Slf4j
@WebFilter(filterName = "CustomerFilter", urlPatterns = "/order/add")
public class CustomerFilter implements Filter {
    @Autowired
    private HandlerExceptionResolver handlerExceptionResolver;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        log.info("----- CustomerFilter init -----");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
                         FilterChain filterChain) throws IOException, ServletException {
        // 获得前端传过来的json数据
        BodyReaderRequestWrapper requestWrapper = new BodyReaderRequestWrapper(
                (HttpServletRequest) servletRequest);
        BufferedReader reader = requestWrapper.getReader();
        StringBuilder sb = new StringBuilder();
        String line;
        while ((line=reader.readLine())!=null) {
            sb.append(line);
        }
        // 使用hutool工具转换为json对象
        JSONObject jsonObject = JSONUtil.parseObj(sb.toString());
        String customer = jsonObject.getStr("customer");
        // 用户在黑名单抛出业务异常，不再继续操作
        if (customer!=null && customer.equals("陈冬")) {
            log.warn("用户被限制下单");
            // filer中直接抛出异常，是无法被ControllerAdvice拦截的
            // 请求按filter -> interceptor -> controllerAdvice -> aspect -> controller的顺序调用
            handlerExceptionResolver.resolveException(
                    (HttpServletRequest) servletRequest,
                    (HttpServletResponse) servletResponse,
                    null,
                    new BusinessException("用户被限制下单"));
        } else {
            // 将requestWrapper和response传给filter链即可
            filterChain.doFilter(requestWrapper, servletResponse);
        }
    }

    @Override
    public void destroy() {
        log.info("----- CustomerFilter destroy -----");
    }
}
